package com.atguigu.spzx.manager.interceptor;

import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.entity.system.SysUserThreadLocalAuthContextUtil;
import com.atguigu.spzx.util.AtguiguAssert;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@Slf4j
public class LoginAuthInterceptor implements HandlerInterceptor {

    @Autowired
    RedisTemplate<String,String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("LoginAuthInterceptor.preHandle");
        String requestURI = request.getRequestURI();
        log.info("LoginAuthInterceptor:"+requestURI);

        String method = request.getMethod();
        System.out.println(method);
        if(method.equals("OPTIONS")){
            return true;
        }
        // 获得token
        String token = request.getHeader("token");
        AtguiguAssert.notNull(token,"用户信息拦截器token失败");

        // 使用token换取用户信息
        String json = redisTemplate.opsForValue().get("user:login:" + token);
        AtguiguAssert.notNull(json,"用户信息拦截器json失败");
        SysUser sysUser = JSON.parseObject(json,SysUser.class);

        // 将用户信息保存到
        SysUserThreadLocalAuthContextUtil.set(sysUser);

        return true;
    }

}
